#include <stdio.h>
#include <string.h>
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "wifi_device.h"
#include "wifi_hotspot_config.h"

static WifiErrorCode wifi_error;
static WifiEvent g_wifiEventHandler = {0};
static void OnHotspotStaJoinHandler(StationInfo *info)
{
    (void)info;
    printf("STA join AP\n");
    return;
}

static void OnHotspotStaLeaveHandler(StationInfo *info)
{
    (void)info;
    printf("HotspotStaLeave:info is null.\n");
    return;
}

static void OnHotspotStateChangedHandler(int state)
{
    printf("HotspotStateChanged:state is %d.\n", state);
    return;
}

static void WiFiInit(void)
{
    printf("<--Wifi Init-->\r\n");
    g_wifiEventHandler.OnHotspotStaJoin = OnHotspotStaJoinHandler;
    g_wifiEventHandler.OnHotspotStaLeave = OnHotspotStaLeaveHandler;
    g_wifiEventHandler.OnHotspotStateChanged = OnHotspotStateChangedHandler;
    wifi_error = RegisterWifiEvent(&g_wifiEventHandler);
    if (wifi_error != WIFI_SUCCESS) {
        printf("register wifi event fail!\r\n");
    } else {
        printf("register wifi event succeed!\r\n");
    }
}

void EnableAp(const char *ssid, const char *psk)
{
    WiFiInit();
    HotspotConfig ap_config = {0};
    strncpy(ap_config.ssid, ssid, WIFI_MAX_SSID_LEN - 1);
    ap_config.ssid[WIFI_MAX_SSID_LEN - 1] = '\0';
    strncpy(ap_config.preSharedKey, psk, WIFI_MAX_KEY_LEN - 1);
    ap_config.preSharedKey[WIFI_MAX_KEY_LEN - 1] = '\0';
    ap_config.securityType = WIFI_SEC_TYPE_PSK;
    if (SetHotspotConfig(&ap_config) != WIFI_SUCCESS) {
        printf("SetHotspotConfig failed, wifi_error = %d\n", wifi_error);
        return;
    }
    wifi_error = EnableHotspot();
    if (wifi_error != WIFI_SUCCESS) {
        printf("EnableHotspot failed, wifi_error = %d\n", wifi_error);
        return;
    }
    return;
}

int DisableAp(void)
{
    return DisableHotspot();
}